package com.ticket.sass.admin.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.ticket.sass.admin.manager.MybatisTenantIgnoreManager;
import com.ticket.sass.admin.manager.ThreadLocalIdInputHolderManager;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @author ywb
 * @date 2024-03-20 10:52
 */
@Component
public class MyCinemaHandler implements TenantLineHandler {
    private final HttpServletRequest request;
    
    public MyCinemaHandler(HttpServletRequest request) {
        this.request = request;
    }
    
    
    @Override
    public Expression getTenantId() {
        IdentityInput identityInput = ThreadLocalIdInputHolderManager.getValue();
        // 检查 MybatisTenantIgnoreManager 是否有值并且其 cinemaId 是否为 true
        return new LongValue(identityInput.getCinemaId());
    }
    
    @Override
    public String getTenantIdColumn() {
        return "cinema_id";
    }
    
    
    // 要忽略的表列表
    private static final List<String> IGNORED_TABLES = Arrays.asList(
        "tenants",
        "tenant_accounts",
        "tenant_cinema_maps",
        "tenant_fund_flows",
        "theme_configs",
        "tenant_wxa_configs",
        "wxa_configs",
        "films",
        "cinema_extends",
        "ticket_server_configs",
        "film_versions",
        // 用户
        "users",
        // 微信用户
        "user_wxs",
        // 影院
        "cinemas",
        // 应用
        "apps",
        // 管理员
        "admins",
        //优惠券
        "coupons",
        "coupon_code_batches",
        "coupon_codes",
        "coupon_user_maps",
        // 地区
        "areas",
        "film_likes",
        "resources",
        // 会员
        "member_cards",
        "member_card_levels",
        "member_card_order_records"
    );
    
    // 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
    @Override
    public boolean ignoreTable(String tableName) {
        MybatisTenantIgnoreManager.IgnoreField ignoreField  = MybatisTenantIgnoreManager.INSTANCE.getValue();
        if (ignoreField != null && ignoreField.getCinemaId() == true) {
            return true;
        }
        // 如果表名在忽略的表列表中，则返回true表示忽略该表
        return IGNORED_TABLES.contains(tableName.toLowerCase());
    }
}